package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: mergeTwoLists
 * @author: chanzhugang
 * @create: 2022/10/22 23:33
 */
public class MergeTwoLists {

    /**
     * 剑指offer 25 合并两个排序的链表
     * https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
     * <p>
     * https://leetcode.cn/problems/merge-sorted-array/： 合并有序数组
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        // 虚拟头节点 + 尾节点
        ListNode dummyHead = new ListNode();
        ListNode tail = dummyHead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                // 尾插法
                tail.next = l1;
                tail = l1;
                l1 = l1.next;
            } else {
                tail.next = l2;
                tail = l2;
                l2 = l2.next;
            }
        }
        // 没处理完的链表，直接追加到tail后面
        if (l1 != null) {
            tail.next = l1;
        }
        if (l2 != null) {
            tail.next = l2;
        }
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        public ListNode() {

        }
    }
}